package artifacts;

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.AbstractListModel;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.JOptionPane;


    
public class GuiBPMView extends JFrame {        
        
		private JPanel contentPane;
		private JTable table;
		private JTable table2;
		private JTextField textField;
		private JTextField textField_1;
		private JTextField textField_2;
		private JTextField textField_3;
		private JTable table_3;
		private JPanel panel_1;
		private JTextField textField_4;
		private JTable table_1;
		private JTable table_2;
		private JTable table_4;
		private JTable table_5;
		private JTextField textField_5;
		private JTextField textField_6;
		private JTextField textField_7;
		private JTable table_6;
		private JComboBox filesToStorage;
		static GuiBPMView frame;
		private JTextPane preview = new JTextPane();
        
        public GuiBPMView(){
		setTitle("Gui");
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 660, 411);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(0, 73, 644, 300);
		contentPane.add(tabbedPane);
		
		table = new JTable();
		
		JPanel panel = new JPanel();
		tabbedPane.addTab("Documents", null, panel, null);
		panel.setLayout(null);
		
		table_3 = new JTable();
		table_3.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int col= table_3.columnAtPoint(e.getPoint());
				if(col < 3)
				{
					infoDocumentos info = new infoDocumentos();
					info.show();
				}
			}
		});
		table_3.setOpaque(false);
		table_3.setModel(new DefaultTableModel(
			new Object[][] {
				{"sdf", "asdf", "asdf","Abrir"},
				{"asdf", "asdf", "asdf","Abrir"},
				{"asdf", "asdf", "asdf","Abrir"},
			},
			new String[] {
				"Documento", "Descripci\u00F3n", "Raz\u00F3n", "Abrir"
			}
		));
		table_3.getColumn("Abrir").setCellRenderer(new ButtonRenderer());
		table_3.getColumn("Abrir").setCellEditor(
	        new ButtonEditor(new JCheckBox(),this));
		table_3.setBounds(368, 62, 164, 182);
		//panel.add(table_3);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(21, 28, 589, 167);
		scrollPane_1.setViewportView(table_3);
		panel.add(scrollPane_1);
		
		JLabel lblCargando = new JLabel("Cargando....");
		lblCargando.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblCargando.setBounds(269, 126, 100, 19);
		panel.add(lblCargando);
		
		table2 = new JTable();

		DefaultTableModel datos2 = new DefaultTableModel();
		datos2.addColumn("Documentos");
		datos2.addColumn("Descripcion");
		datos2.addColumn("Razon");
		String[] row4 = {"Cuatro","Desc","razon1"};
		datos2.addRow(row4);
		String[] row5 = {"Cinco","Desc","razon1"};
		datos2.addRow(row5);
		String[] row6 = {"Seis","Desc","razon1"};
		datos2.addRow(row6);
		
		panel_1 = new JPanel();
		tabbedPane.addTab("NLQ", null, panel_1, null);
		panel_1.setLayout(null);
		
		JLabel lblQuery = new JLabel("Query:");
		lblQuery.setBounds(30, 24, 46, 14);
		panel_1.add(lblQuery);
		
		textField_4 = new JTextField();
		textField_4.setBounds(79, 21, 422, 20);
		panel_1.add(textField_4);
		textField_4.setColumns(10);
		
		JButton btnGo = new JButton("Find");
		btnGo.setBounds(511, 20, 89, 23);
		panel_1.add(btnGo);
		
		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(30, 52, 589, 167);
		
		
		table_1 = new JTable();
		table_1.setModel(new DefaultTableModel(
			new Object[][] {
				{"ssss", "dddd", "ddd"},
				{"sfsdf", "fsdf", "ssd"},
				{"asfas", "sfasdf", "asdfasdfasd"},
			},
			new String[] {
				"Documento", "Descripci\u00F3n", "Raz\u00F3n"
			}
		));
		table_1.setOpaque(false);
		table_1.setBounds(32, 213, 587, 48);
		//panel_1.add(table_1);
		scrollPane_2.setViewportView(table_1);
		panel_1.add(scrollPane_2);
		
		JPanel panel_2 = new JPanel();
		tabbedPane.addTab("Social Network", null, panel_2, null);
		panel_2.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(48, 80, 148, 154);
		panel_2.add(scrollPane);
		
		table_2 = new JTable();
		table_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				workerInfo worker = new workerInfo();
				worker.show();
			}
		});
		table_2.setModel(new DefaultTableModel(
			new Object[][] {
				{"Juan Perez"},
			},
			new String[] {
				"Worker Name"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane.setViewportView(table_2);
		
		JScrollPane scrollPane_3 = new JScrollPane();
		scrollPane_3.setBounds(244, 80, 148, 154);
		panel_2.add(scrollPane_3);
		
		table_4 = new JTable();
		table_4.setModel(new DefaultTableModel(
			new Object[][] {
				{"John Perez"},
			},
			new String[] {
				"Worker Name"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane_3.setViewportView(table_4);
		
		JScrollPane scrollPane_4 = new JScrollPane();
		scrollPane_4.setBounds(440, 80, 148, 154);
		panel_2.add(scrollPane_4);
		
		table_5 = new JTable();
		table_5.setModel(new DefaultTableModel(
			new Object[][] {
				{"Bruce Gomez"},
			},
			new String[] {
				"Worker Name"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane_4.setViewportView(table_5);
		
		JTextPane txtpnWorkersThatPerformed = new JTextPane();
		txtpnWorkersThatPerformed.setBackground(SystemColor.control);
		txtpnWorkersThatPerformed.setEditable(false);
		txtpnWorkersThatPerformed.setText("Workers that performed this task in previous workflow instance");
		txtpnWorkersThatPerformed.setBounds(48, 11, 148, 58);
		panel_2.add(txtpnWorkersThatPerformed);
		
		JTextPane txtpnWorkersThatPerformed_1 = new JTextPane();
		txtpnWorkersThatPerformed_1.setBackground(SystemColor.control);
		txtpnWorkersThatPerformed_1.setEditable(false);
		txtpnWorkersThatPerformed_1.setText("Workers that performed previous task in this workflow");
		txtpnWorkersThatPerformed_1.setBounds(244, 11, 148, 58);
		panel_2.add(txtpnWorkersThatPerformed_1);
		
		JTextPane txtpnWorkersThatCreated = new JTextPane();
		txtpnWorkersThatCreated.setEditable(false);
		txtpnWorkersThatCreated.setBackground(SystemColor.control);
		txtpnWorkersThatCreated.setText("Workers that created documents in this task in previous executions");
		txtpnWorkersThatCreated.setBounds(440, 11, 148, 58);
		panel_2.add(txtpnWorkersThatCreated);
		
		JPanel panel_3 = new JPanel();
		tabbedPane.addTab("Task Workflow", null, panel_3, null);
		panel_3.setLayout(null);
		
		JScrollPane scrollPane_5 = new JScrollPane();
		scrollPane_5.setBounds(37, 39, 170, 206);
		panel_3.add(scrollPane_5);
		
		JList list = new JList();
		list.setModel(new AbstractListModel() {
			String[] values = new String[] {"Task 1", "Task 2", "Task 3"};
			public int getSize() {
				return values.length;
			}
			public Object getElementAt(int index) {
				return values[index];
			}
		});
		scrollPane_5.setViewportView(list);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new TitledBorder(null, "Task Information", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_4.setBounds(233, 33, 380, 212);
		panel_3.add(panel_4);
		panel_4.setLayout(null);
		
		JLabel lblTaskName = new JLabel("Task Name:");
		lblTaskName.setBounds(10, 25, 79, 14);
		panel_4.add(lblTaskName);
		
		JLabel lblDomain = new JLabel("Executed by:");
		lblDomain.setBounds(194, 25, 79, 14);
		panel_4.add(lblDomain);
		
		JLabel lblDateExecution = new JLabel("Date execution:");
		lblDateExecution.setBounds(10, 50, 79, 14);
		panel_4.add(lblDateExecution);
		
		JLabel lblInformationUsed = new JLabel("Information used:");
		lblInformationUsed.setBounds(10, 75, 113, 14);
		panel_4.add(lblInformationUsed);
		
		JScrollPane scrollPane_6 = new JScrollPane();
		scrollPane_6.setBounds(10, 100, 174, 101);
		panel_4.add(scrollPane_6);
		
		JList list_1 = new JList();
		scrollPane_6.setViewportView(list_1);
		
		JLabel lblInformationCreated = new JLabel("Information created:");
		lblInformationCreated.setBounds(194, 75, 149, 14);
		panel_4.add(lblInformationCreated);
		
		JScrollPane scrollPane_7 = new JScrollPane();
		scrollPane_7.setBounds(194, 100, 165, 101);
		panel_4.add(scrollPane_7);
		
		JList list_2 = new JList();
		scrollPane_7.setViewportView(list_2);
		
		textField_5 = new JTextField();
		textField_5.setBounds(95, 22, 86, 20);
		panel_4.add(textField_5);
		textField_5.setColumns(10);
		
		textField_6 = new JTextField();
		textField_6.setColumns(10);
		textField_6.setBounds(273, 22, 86, 20);
		panel_4.add(textField_6);
		
		textField_7 = new JTextField();
		textField_7.setColumns(10);
		textField_7.setBounds(95, 47, 86, 20);
		panel_4.add(textField_7);
		
		JLabel lblTaskList = new JLabel("Task List");
		lblTaskList.setBounds(37, 22, 69, 14);
		panel_3.add(lblTaskList);
		
		JPanel panel_5 = new JPanel();
		tabbedPane.addTab("Document Storage", null, panel_5, null);
		panel_5.setLayout(null);
		
		JButton btnAddNewFile = new JButton("Add New File");
		btnAddNewFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser chooser = new JFileChooser();
				int sel = chooser.showOpenDialog(frame);
				if (sel == JFileChooser.APPROVE_OPTION){
					copy(chooser.getSelectedFile(),new File("D:/Archivos/guardar/"+chooser.getSelectedFile().getName()));
					addFileToCombo(chooser.getSelectedFile().getName());
				}
			}
		});
		btnAddNewFile.setBounds(58, 22, 165, 23);
		panel_5.add(btnAddNewFile);
		
		JLabel lblDomain_1 = new JLabel("Domain:");
		lblDomain_1.setBounds(10, 91, 60, 14);
		panel_5.add(lblDomain_1);
		
		JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"Dominio 1", "Dominio 2", "Dominio 3"}));
		comboBox.setBounds(58, 88, 165, 20);
		panel_5.add(comboBox);
		
		JButton btnCheck = new JButton("Check");
		btnCheck.setBounds(136, 132, 89, 23);
		panel_5.add(btnCheck);
		
		JLabel lblDescriptors = new JLabel("Descriptors");
		lblDescriptors.setBounds(280, 26, 119, 14);
		panel_5.add(lblDescriptors);
		
		JScrollPane scrollPane_8 = new JScrollPane();
		scrollPane_8.setBounds(280, 40, 143, 120);
		panel_5.add(scrollPane_8);
		
		table_6 = new JTable();
		table_6.setModel(new DefaultTableModel(
			new Object[][] {
				{"Descriptor 1", false},
				{"Descriptor 2", false},
			},
			new String[] {
				"Descriptor", ""
			}
		) {
			Class[] columnTypes = new Class[] {
				Object.class, Boolean.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
		});
		scrollPane_8.setViewportView(table_6);
		
		JButton btnStorage = new JButton("Storage");
		btnStorage.setBounds(280, 238, 89, 23);
		panel_5.add(btnStorage);
		
		JLabel lblFiles = new JLabel("Files:");
		lblFiles.setBounds(10, 63, 30, 14);
		panel_5.add(lblFiles);
		
		filesToStorage = new JComboBox();
		filesToStorage.addItem(null);
		filesToStorage.setBounds(58, 60, 165, 20);
		panel_5.add(filesToStorage);
		
		JButton btnDelete = new JButton("Delete");
		btnDelete.setBounds(43, 132, 89, 23);
		panel_5.add(btnDelete);
		
		preview.setEditable(false);
		preview.setBounds(433, 38, 196, 189);
		panel_5.add(preview);
		
		filesToStorage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(filesToStorage.getSelectedItem() != null)
					loadPreview(filesToStorage.getSelectedItem().toString());
			}
		});
		
		JLabel lblPreview = new JLabel("Preview");
		lblPreview.setBounds(438, 23, 46, 14);
		panel_5.add(lblPreview);
		
		
		JLabel lblTask = new JLabel("Task:");
		lblTask.setBounds(10, 27, 46, 14);
		contentPane.add(lblTask);
		
		//Carga el combo con los archivos que estan en el directorio
		cargarCombo();
		
		JLabel lblWorker = new JLabel("Worker:");
		lblWorker.setBounds(157, 27, 46, 14);
		contentPane.add(lblWorker);
		
		JLabel lblGroup = new JLabel("Group:");
		lblGroup.setBounds(312, 27, 46, 14);
		contentPane.add(lblGroup);
		
		JLabel lblWorkflow = new JLabel("Workflow:");
		lblWorkflow.setBounds(486, 27, 61, 14);
		contentPane.add(lblWorkflow);
		
		textField = new JTextField();
		textField.setBounds(40, 24, 86, 20);
		textField.setEditable(false);
		textField.setName("task");
		contentPane.add(textField);
		textField.setColumns(10);
		
		textField_1 = new JTextField();
		textField_1.setBounds(202, 24, 86, 20);
		textField_1.setEditable(false);
		contentPane.add(textField_1);
		textField_1.setColumns(10);
		
		textField_2 = new JTextField();
		textField_2.setBounds(359, 24, 86, 20);
		textField_2.setEditable(false);
		contentPane.add(textField_2);
		textField_2.setColumns(10);
		
		textField_3 = new JTextField();
		textField_3.setBounds(548, 24, 86, 20);
		textField_3.setEditable(false);
		contentPane.add(textField_3);
		textField_3.setColumns(10);
		
	}
	
	private void loadPreview(String file)
	{
		//JOptionPane.showMessageDialog(null, "file: "+file);
		if(file != null)
			preview.setText(file);
	}
	
	/** 
     * Copia un solo archivo 
     * @param src 
     * @param dst 
     * @throws IOException 
     */ 
    public void copy(File src, File dst) 
    { 
    	try{
        InputStream in = new FileInputStream(src); 
        OutputStream out = new FileOutputStream(dst); 
         
         
        byte[] buf = new byte[1024]; 
        int len; 
        while ((len = in.read(buf)) > 0) { 
            out.write(buf, 0, len); 
        } 
        in.close(); 
        out.close(); 
    	}
    	catch(Exception e){}
    } 
	
	private void cargarCombo()
	{
		File directorio = new File("D:/Archivos/guardar");
		String [] ficheros = directorio.list();
		for (int i = 0; i < ficheros.length; i++) {
			filesToStorage.addItem(ficheros[i]);
		}
	}
	
	public void addFileToCombo(String file)
	{
		filesToStorage.removeItem(file);
		filesToStorage.addItem(file);
	}
	
	private String getContenidoHTML() throws IOException 
	{
	    URL url = new URL("http://localhost/jacamo/files/documento.txt");
	    URLConnection uc = url.openConnection();
	    uc.connect();
	    //Creamos el objeto con el que vamos a leer
	    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
	    String inputLine;
	    String contenido = "";
	    while ((inputLine = in.readLine()) != null) {
	        contenido += inputLine + "\n";
	    }
	    in.close();
	    return contenido;
	}
}
class ButtonRenderer extends JButton implements TableCellRenderer {

	  public ButtonRenderer() {
	    setOpaque(true);
	  }

	  public Component getTableCellRendererComponent(JTable table, Object value,
	      boolean isSelected, boolean hasFocus, int row, int column) {
	    if (isSelected) {
	      setForeground(table.getSelectionForeground());
	      setBackground(table.getSelectionBackground());
	    } else {
	      setForeground(table.getForeground());
	      setBackground(UIManager.getColor("Button.background"));
	    }
	    setText((value == null) ? "" : value.toString());
	    return this;
	  }
	}

	/**
	 * @version 1.0 11/09/98
	 */

	class ButtonEditor extends DefaultCellEditor {
	  protected JButton button;

	  private String label;
	  
	  private int row;

	  private boolean isPushed;
	  private GuiBPMView principal;

	  public ButtonEditor(JCheckBox checkBox,GuiBPMView principal) {
	    super(checkBox);
	    this.principal = principal;
	    button = new JButton();
	    button.setOpaque(true);
	    button.addActionListener(new ActionListener() {
	      public void actionPerformed(ActionEvent e) {
	        fireEditingStopped();
	      }
	    });
	  }

	  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
	    if (isSelected) {
	      button.setForeground(table.getSelectionForeground());
	      button.setBackground(table.getSelectionBackground());
	    } else {
	      button.setForeground(table.getForeground());
	      button.setBackground(table.getBackground());
	    }
	    label = (value == null) ? "" : value.toString();
	    this.row = row;
	    button.setText(label);
	    isPushed = true;
	    return button;
	  }

	  public Object getCellEditorValue() {
	    if (isPushed) {
	    	try{
	    	URL url = new URL("http://localhost/jacamo/files/documento.txt");
		    URLConnection uc = url.openConnection();
		    uc.connect();
		    //Creamos el objeto con el que vamos a leer
		    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
		    String inputLine;
		    String contenido = "";
		    while ((inputLine = in.readLine()) != null) {
		        contenido += inputLine + "\n";
		    }
		    in.close();
		    Editor editor = new Editor("documento.txt");
		    editor.setPrincipal(principal);
		    editor.cargarTexto(contenido);
	    	}
	    	catch(Exception e){}
	    }
	    isPushed = false;
	    return new String(label);
	  }
	  
	  private String getContenidoHTML() throws IOException 
		{
		    URL url = new URL("http://localhost/jacamo/files/documento.txt");
		    URLConnection uc = url.openConnection();
		    uc.connect();
		    //Creamos el objeto con el que vamos a leer
		    BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
		    String inputLine;
		    String contenido = "";
		    while ((inputLine = in.readLine()) != null) {
		        contenido += inputLine + "\n";
		    }
		    in.close();
		    return contenido;
		}

	  public boolean stopCellEditing() {
	    isPushed = false;
	    return super.stopCellEditing();
	  }

	  protected void fireEditingStopped() {
	    super.fireEditingStopped();
	  }
	}
